<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>平均效率展示</title>
    <style>
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
        }

        th,
        td {
            padding: 12px 15px;
            text-align: center;
            border-bottom: 1px solid #dddddd;
            transition: all 0.3s ease;
        }

        th {
            background-color: #009879;
            color: #ffffff;
            font-weight: bold;
        }

        tr:hover {
            background-color: #ffeb3b;
            transform: scale(1.05);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            font-weight: bold;
            transition: all 0.3s ease;
        }

        tr:nth-child(even) {
            background-color: #f3f3f3;
        }

        h1 {
            color: #009879;
            margin-bottom: 30px;
            text-align: center;
        }

        #query-form {
            margin-bottom: 30px;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        #query-form label {
            font-weight: bold;
        }

        #query-form button {
            padding: 8px 16px;
            background-color: #009879;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #query-form button:hover {
            background-color: #007f63;
        }
    </style>
    <!-- 引入本地 ECharts 库，假设文件名为 echarts.min.js，放在 static/js 目录下 -->
    <script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
</head>

<body>
    <div class="container">

        <form id="query-form">
            <label for="query-date">查询日期：</label>
            <input type="date" id="query-date" name="query-date" required>

            <label for="shift">查询班次：</label>
            <select id="shift" name="shift" required>
                <option value="D">白班</option>
                <option value="N">夜班</option>
            </select>
            <label for="product">产品名称：</label>
            <select id="product" name="product" required>
                {% for product in product_names %}
                <option value="{{ product }}">{{ product }}</option>
                {% endfor %}
            </select>

            <button type="submit">查询</button>
            <button id="save-button">保存为图片</button>
            <span id="update-time" style="margin-left: 15px;">最后更新时间：</span>
        </form>
        <div class="pngdown">
            <div style="text-align: center; margin-bottom: 20px;">
                <h2>平均效率展示</h2>
                <h3 id="query-info"></h3>
            </div>
            <div id="result-container"
                style="margin-top: 30px; padding: 20px; background-color: #f9f9f9; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1);">
                <!-- <h3 style="color: #009879; margin-bottom: 20px;">查询结果</h3> -->
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>线别</th>
                            <th>数量</th>
                            <th>Eta</th>
                            <th>Uoc</th>
                            <th>Isc</th>
                            <th>FF</th>
                            <th>Rs</th>
                            <th>Rsh</th>
                            <th>IRev2 < 0</th>
                            <th>IRev2 < 0.05</th>
                            <th>IRev2 < 0.2</th>
                            <th>IRev2 < 0.3</th>
                        </tr>
                    </thead>
                    <tbody id="data-body">
                        <!-- 数据将动态插入 -->
                    </tbody>
                </table>
            </div>
        </div>
        <!-- 添加一个 div 用于渲染 ECharts 图表 -->
        <div style="margin-top: 30px; max-width: 100%;">
            <h2 style="text-align: center;">每条线的平均效率柱形图</h2>
            <div id="efficiencyChart" style="height: 400px;"></div>
        </div>
    </div>
</body>

</html>

<script src="{{ url_for('static', filename='js/html2canvas.min.js') }}"></script>
<script>
    // 自动填充日期和班次
    function autoFillForm() {
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const currentTime = hours * 60 + minutes;

        let date = new Date();
        let shift = 'D';

        if (currentTime >= 0 && currentTime < 510) { // 00:00-08:30
            date.setDate(date.getDate() - 1);
            shift = 'N';
        } else if (currentTime >= 510 && currentTime < 1230) { // 08:30-20:30
            shift = 'D';
        } else { // 20:30-24:00
            shift = 'N';
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`;

        document.getElementById('query-date').value = formattedDate;
        document.getElementById('shift').value = shift;
    }

    // 页面加载时调用
    autoFillForm();
    // 添加排序功能
    const sortTable = (columnIndex, order) => {
        const table = document.querySelector('table');
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));

        rows.sort((a, b) => {
            const aValue = a.querySelectorAll('td')[columnIndex].textContent;
            const bValue = b.querySelectorAll('td')[columnIndex].textContent;

            // 尝试将值转换为数字
            const numA = parseFloat(aValue);
            const numB = parseFloat(bValue);

            // 如果两个值都是有效数字，则按数字排序
            if (!isNaN(numA) && !isNaN(numB)) {
                return order === 'asc' ? numA - numB : numB - numA;
            }
            // 否则按字符串排序
            else {
                return order === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
            }
        });

        tbody.innerHTML = '';
        rows.forEach(row => tbody.appendChild(row));
    };


    // 为表头添加点击事件
    const headers = document.querySelectorAll('th');
    headers.forEach((header, index) => {
        header.addEventListener('click', () => {
            const currentOrder = header.dataset.order || 'asc';
            sortTable(index, currentOrder);
            header.dataset.order = currentOrder === 'asc' ? 'desc' : 'asc';
        });
    });
    // 添加保存按钮
    const saveButton = document.getElementById('save-button');
    saveButton.style.padding = '8px 16px';
    saveButton.style.backgroundColor = '#009879';
    saveButton.style.color = 'white';
    saveButton.style.border = 'none';
    saveButton.style.borderRadius = '4px';
    saveButton.style.cursor = 'pointer';

    // 保存为图片功能
    saveButton.addEventListener('click', () => {
        html2canvas(document.querySelector('.pngdown')).then(canvas => {
            const link = document.createElement('a');
            link.download = 'efficiency-table.png';
            link.href = canvas.toDataURL('image/png');
            link.click();
        });
    });

    document.getElementById('query-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        document.getElementById('update-time').textContent = '最后更新时间：';

        // 原代码存在语法错误，对象字面量内不能直接定义变量，现将日期格式化逻辑移到对象外部
        const rawDate = document.getElementById('query-date').value;
        const dateObj = new Date(rawDate);
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const formattedDate = `${year}${month}${day}`;
        const formData = {
            query_date: formattedDate,
            shift: document.getElementById('shift').value,
            product: document.getElementById('product').value
        };

        try {
            const response = await fetch('/api/query_efficiency', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const data = await response.json();
            console.log(data);
            renderTable(data.avgeta);
            document.getElementById('query-info').textContent = '查询日期：' + document.getElementById('query-date').value + ' | 班次：' + (document.getElementById('shift').value === 'D' ? '白班' : '夜班') + ' | 产品：' + document.getElementById('product').value + ' | 数据库更新时间：' + data.update_time.last_updated;
            document.getElementById('update-time').textContent = '最后更新时间：' + data.update_time.last_updated;
        } catch (error) {
            console.error('Error:', error);
            alert('查询失败，请稍后重试');
        }
    });

    function renderTable(data) {
        const tbody = document.getElementById('data-body');
        tbody.innerHTML = data.map((item, index) => `
        <tr>
            <td>${index + 1}</td>
            <td>${item.line}</td>
            <td>${Math.round(item.quantity)}</td>
            <td>${Number(item.eta1).toFixed(4)}</td>
            <td>${Number(item.uoc1).toFixed(4)}</td>
            <td>${Number(item.isc1).toFixed(4)}</td>
            <td>${Number(item.ff1).toFixed(4)}</td>
            <td>${Number(item.rs).toFixed(4)}</td>
            <td>${Number(item.rsh).toFixed(4)}</td>
            <td>${item.irev2_lt_0}</td>
            <td>${item.irev2_lt_0_05}</td>
            <td>${item.irev2_lt_0_2}</td>
            <td>${item.irev2_lt_0_3}</td>
        </tr>
    `).join('');

        // 提取所有 eta1 值并排序
        const etaValues = data.map(item => Number(item.eta1));
        const sortedEtaValues = [...etaValues].sort((a, b) => b - a); // 降序排序
        const top5 = sortedEtaValues.slice(0, 5);

        // 计算最小值和最大值，并保留1位小数
        const minEta = Math.round(Math.min(...etaValues) * 10) / 10;
        const maxEta = Math.round(Math.max(...etaValues) * 10) / 10;

        // 初始化 ECharts 实例
        const chartDom = document.getElementById('efficiencyChart');
        const myChart = echarts.init(chartDom);

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: data.map(item => item.line)
            },
            yAxis: {
                type: 'value',
                min: minEta - 0.1,
                max: maxEta + 0.1
            },
            series: [{
                data: data.map(item => Number(item.eta1)),
                type: 'bar',
                label: {
                    show: true,
                    position: 'top',
                    // 修改 formatter 以显示 3 位小数
                    formatter: (params) => {
                        return params.value.toFixed(3);
                    }
                }
            }]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
</script>